package com.wgj.android.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jiaai.xui.XUI;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.XBitmapUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.imageload.XImage;
import com.jiaai.xui.utils.share.ShareUtils;
import com.jiaai.xui.utils.share.entity.Share;
import com.jiaai.xui.view.widget.CircleImageView;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.service.WXShareAccesslibilityService;
import com.wgj.android.dialog.ManyDiadlog;
import com.wgj.android.dialog.ShareDiadlog;
import com.wgj.android.entity.Member;
import com.wgj.android.entity.SystemConfg;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;

import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/8.
 */

public class MyShareActivity extends AppCompatActivity implements ShareDiadlog.OnShareListener,ManyDiadlog.ManyDiadlogListener {
    @BindView(R.id.qrCode)
    ImageView ivQrcode;
    @BindView(R.id.avater)
    CircleImageView ivAvater;

    @BindView(R.id.nickName)
    TextView tvNickName;

    private int shareType;

    private Member member;

    private SystemConfg confg;
    private Share share;

    private ShareDiadlog shareDiadlog;
    private ManyDiadlog manyDiadlog;

    public  static void  openMyShareUI(Context context){
        Intent intent=new Intent(context,MyShareActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
        getWindow().setFlags(flag, flag);
        super.setContentView(R.layout.my_share_activity);
        shareDiadlog=new ShareDiadlog().setOnShareListener(this);
        manyDiadlog=new ManyDiadlog().setDiadlogListener(this);
        shareType=getIntent().getIntExtra("type",0);
        member= CacheUtils.getMember();
        confg=CacheUtils.getSystemConfig();
        ButterKnife.bind(this);

        share=new Share();
        share.setThumBitmap(XBitmapUtils.getBitmapFromDrawable(XUI.getDrawable(R.mipmap.logo)));
        share.setTitle(confg.getSharetitle());
        share.setWebUrl(member.getShareUrl());
        share.setDescription(confg.getSharecontent());
        XImage.getInstance().load(ivAvater, CacheUtils.getMember().getAvater());
        tvNickName.setText(CacheUtils.getMember().getM_nick());
        XImage.getInstance().load(ivQrcode, WGJAPI.BASEURL+"page/getqr?pid="+CacheUtils.getMember().getM_id());
    }

    @OnClick(R.id.qrBgg) void  onClick(View view){
        if(shareType==0){
            shareDiadlog.show(getSupportFragmentManager(),"shareDialog");
        }else {
            manyDiadlog.show(getSupportFragmentManager(),"manyDiadlog");
        }

    }
    @Override
    public void onItemClick(int index) {
        switch (index){
            case 0:
                String savePath=getSDCardPath()+File.separator+"旺旺通"+File.separator+"ScreenImage";
                File path=new File(savePath);
                if(!path.exists()){
                    path.mkdirs();
                }
                String filePath= savePath+File.separator+member.getM_id()+"_share1.png";
                File file=new File(filePath);
                GetandSaveCurrentImage(file);
                break;
            case 1:

                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setPrimaryClip(ClipData.newPlainText(null, member.getShareUrl()));
                XToast.success("分享接连已复制到粘贴板,可以发送给朋友们了.");
                break;
            case 2:
                WXShareAccesslibilityService.start();
                ComponentName comp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
                Intent it = new Intent();
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要加这个不然会报错
                it.setComponent(comp);
                startActivity(it);
                break;

        }

    }

    /**
     * 获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage(File file)
    {
        //1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int w = display.getWidth();
        int h = display.getHeight();

        Bitmap Bmp = Bitmap.createBitmap( w, h, Bitmap.Config.ARGB_8888 );
        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();


        //3.保存Bitmap
        try {

            file.createNewFile();
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                getApplication().sendBroadcast(intent);
                XToast.success("截屏文件已保存至"+file.getPath(),3000);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取SDCard的目录路径功能
     * @return
     */
    private String getSDCardPath(){
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if(sdcardExist){
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }


    @Override
    public void onShareWeiXin() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            ShareUtils.shareWeiXin(getApplication(),share,confg.getWXAppId(),false);
            shareDiadlog.dismiss();
        }
    }

    @Override
    public void onShareFriends() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            ShareUtils.shareWeiXin(getApplication(),share,confg.getWXAppId(),true);
            shareDiadlog.dismiss();
        }
    }
    @Override
    public void onShareSpaceBut() {
        XToast.error("暂未开放");
    }
    @Override
    public void onShareQQ() {
        XToast.error("暂未开放");
    }

    @Override
    public void onlinkButBut() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(null, member.getShareUrl()));
        XToast.success("分享接连已复制到粘贴板,可以发送给朋友们了.");
    }

    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }




}
